<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class UserMoneyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user_id = 0;

    protected $money = 0;

    /**
     * 1 = 增加余额 2 = 减少余额
     */
    protected $type = 1;

    /**
     * Create a new job instance.
     */
    public function __construct($user_id, $money, $type)
    {
        $this->user_id = $user_id;
        $this->money = $money;
        $this->type = $type;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        //这里用REDIS做个幂等判断 防止重复入账
        $value = Cache::get($this->user_id);

        //如果用户没入过账则入账
        if (empty($value)) {
            Cache::set($this->user_id, $this->money);

            // ... 这里处理账户变更逻辑 假设用户余额字段是money
            $user = User::find($this->user_id);
            $user->money = bcadd($user->money, $this->money, 2);
            $user->save();

        }

        //如果有相等的金额则表示已经入过账了
        if ($this->money == $value) {
            $this->delete();
        }
    }
}
